package com.shuaigef.springbootinit.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shuaigef.springbootinit.common.Result;
import com.shuaigef.springbootinit.model.entity.Message;
import com.shuaigef.springbootinit.utils.MoonshotAiUtils;
import kotlin.text.Charsets;
import okhttp3.*;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;



@RestController
@RequestMapping("/aichat")
public class AIChatController {
    public static final String API_KEY = "sk-U1xkvmJQAphHeEqk5eoMA7mNcnudf4Ms1fV3NKpcpEiVADIM";
    final static MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
    final OkHttpClient client = new OkHttpClient().newBuilder()
            .readTimeout(6000, TimeUnit.SECONDS)
            .build();
    private static final Logger log = LoggerFactory.getLogger(AIChatController.class);

    @PostMapping("/chat")
    public SseEmitter mainChat(
            @org.springframework.web.bind.annotation.RequestBody Message message,
            HttpSession session
    ) throws Exception {
        System.out.println("ID: " + session.getId());

        if (session.getAttribute("messages") == null) {
            session.setAttribute("messages", new ArrayList<Message>());
        }
        ArrayList<Message> messages = (ArrayList<Message>) session.getAttribute("messages");
        System.err.println(message);
        message.setRole("user");
        // 清理无效的空对象
        messages.removeIf(msg -> msg.getRole() == null || msg.getRole().isEmpty() ||
                msg.getContent() == null || msg.getContent().isEmpty());

        messages.add(message);
        // 打印请求参数，确保格式正确
        String requestBody = new cn.hutool.json.JSONObject()
                .putOpt("model", "moonshot-v1-8k")
                .putOpt("messages", messages)
                .putOpt("stream", true)
                .putOpt("temperature", 1)
                .toString();
        System.out.println("Request Body: " + requestBody);

        Request okhttpRequest = new Request.Builder()
                .url("https://api.moonshot.cn/v1/chat/completions")
                .post(RequestBody.create(requestBody, MediaType.get("application/json")))
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();

        Response response = client.newCall(okhttpRequest).execute();

        SseEmitter emitter = new SseEmitter(-1L);

        CompletableFuture.runAsync(() -> {
            try {
                StringBuilder results = new StringBuilder();

                InputStream inputStream = response.body().byteStream();

                byte[] buffer = new byte[1024 * 8];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    String respStr = new String(buffer, 0, len, Charsets.UTF_8);
                    System.err.println(respStr);
                    if (respStr.isEmpty()) {
                        continue;
                    }

                    String[] lines = respStr.split("\n");
                    for (String line : lines) {
                        if (line.equals("data: [DONE]")) {
                        } else if (line.startsWith("data:")) {
                            System.out.println(line);
                            String jsonData = line.replace("data:", "").trim();
                            JSONObject jsonObj = JSON.parseObject(jsonData);
                            if (jsonObj.getJSONArray("choices") != null &&
                                    jsonObj.getJSONArray("choices").size() > 0 &&
                                    jsonObj.getJSONArray("choices").getJSONObject(0).getJSONObject("delta") != null &&
                                    jsonObj.getJSONArray("choices").getJSONObject(0).getJSONObject("delta").getString("content") != null) {
                                String content = jsonObj.getJSONArray("choices")
                                        .getJSONObject(0)
                                        .getJSONObject("delta")
                                        .getString("content");
                                System.err.println(content);
                                results.append(content);
                                emitter.send(content);
                            }
                        } else if (line.contains("error_msg")) {
                            String errorMsg = JSON.parseObject(line).getString("error_msg");
                            emitter.send(errorMsg);
                            System.err.println("Error: " + errorMsg);
                            break;
                        }
                    }
                }
                messages.add(Message.builder().role("assistant").content(results.toString()).build());
                session.setAttribute("messages", messages);
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    emitter.send("Error: " + e.getMessage());
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            } finally {
                emitter.complete();
            }
        });
        return emitter;
    }
    // 获取历史记录
        @GetMapping("/get")
        public ResponseBodyEmitter get(HttpSession session) {
            ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L);

            CompletableFuture.runAsync(() -> {
                try {
                    ArrayList<Message> messages = (ArrayList<Message>) session.getAttribute("messages");
                    if (messages != null) {
                        for (Message msg : messages) {
                            emitter.send(JSON.toJSONString(msg) + "\n");
                            TimeUnit.MILLISECONDS.sleep(100);
                        }
                    }
                    emitter.complete();
                } catch (Exception e) {
                    emitter.completeWithError(e);
                }
            });

            return emitter;
        }

        // 清除会话
        @GetMapping("/clear")
        public Result clear(HttpSession session) {
            session.removeAttribute("messages");
            return Result.success("Session cleared");
        }
    @PostMapping("/uploadFileToKimi")
    public String uploadFileToKimi(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select a file to upload.";
        }

        try {
            // 修改：使用绝对路径确保目录有效
            Path uploadPath = Paths.get(System.getProperty("user.dir"), "uploads");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 构建目标文件路径
            Path filePath = uploadPath.resolve(file.getOriginalFilename());
            // 保存文件
            file.transferTo(filePath.toFile());

            return "File uploaded successfully: " + file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file: " + e.getMessage();
        }
    }

    @PostMapping("/sendFileToKimi")
    public String sendFileToKimi(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Please select an image to upload.";
        }

        try {
            // 修改：使用绝对路径确保目录有效
            Path uploadPath = Paths.get(System.getProperty("user.dir"), "uploads");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 构建目标文件路径
            Path filePath = uploadPath.resolve(file.getOriginalFilename());
            // 保存文件
            file.transferTo(filePath.toFile());

            // 使用 MoonshotAiUtils 的 uploadFile 方法上传文件
            File savedFile = filePath.toFile();
            String uploadResponse = MoonshotAiUtils.uploadFile(savedFile);

            return "Image uploaded to Moonshot: " + uploadResponse;
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload image: " + e.getMessage();
        }
    }
}

